package com.jiyun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiyun.mapper.AdminMapper;
import com.jiyun.pojo.Admin;
import com.jiyun.service.AdminService;
import com.jiyun.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    AdminMapper adminMapper;
    @Override
    public R login(Admin admin) {
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(Admin::getUsername,admin.getUsername());
        qw.eq(Admin::getPassword,admin.getPassword());
        Admin adminDB = adminMapper.selectOne(qw);
        if(adminDB==null){
            return R.error();
        }
        return R.ok().data("admin",adminDB);
    }

    @Override
    public R updatelevel(Integer id) {
        Admin admin = adminMapper.selectById(id);
        admin.setLevel("维修工");
        adminMapper.updateById(admin);
        return R.ok();
    }

    @Override
    public R sendyzm(Integer yzm) {
        Random random = new Random();
        int fourDigitRandomNumber = 1000 + random.nextInt(9000);
        System.out.println("验证码: " + fourDigitRandomNumber);
        return R.ok().data("yzm",fourDigitRandomNumber);
    }

    @Override
    public R findAdmin(Admin admin) {
        List<Admin> list = adminMapper.findAdmin(admin);
        return R.ok().data("list",list);
    }

    @Override
    public R register(Admin admin) {
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(Admin::getUsername,admin.getUsername());
        Admin adminDB = adminMapper.selectOne(qw);
        if(adminDB!=null){
            return R.error().message("该账号已经被注册");
        }
        admin.setPhoto("https://img.itouxiang.com/m12/3b/40/c93bcb7cc178.jpg");
        admin.setLevel("普通用户");
        adminMapper.insert(admin);
        return R.ok();
    }

    @Override
    public R add(Admin admin) {
        if(admin.getId()==null){
            admin.setPhoto("https://img.itouxiang.com/m12/3b/40/c93bcb7cc178.jpg");
            admin.setLevel("普通用户");
            adminMapper.insert(admin);
        }else {
            adminMapper.updateById(admin);
        }

        return R.ok();
    }

    @Override
    public R deleteAdmin(Integer id) {
        adminMapper.deleteById(id);
        return R.ok();
    }
}
